<template>
  <div class="attendance-container">
    <el-card class="attendance-card">
      <template #header>
        <div class="card-header">
          <span>考勤管理</span>
          <div>
            <el-button type="primary" @click="handleImport">
              <el-icon><Upload /></el-icon>
              导入考勤
            </el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.employeeName" placeholder="请输入员工姓名" clearable />
        </el-form-item>
        <el-form-item label="月份">
          <el-date-picker
            v-model="searchForm.month"
            type="month"
            value-format="YYYY-MM"
            placeholder="选择月份"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="employeeId" label="员工编号" width="150" />
        <el-table-column prop="employeeName" label="员工姓名" width="200" />
        <el-table-column prop="workDays" label="工作天数" width="200" />
        <el-table-column prop="absentDays" label="缺勤天数" width="200" />
        <el-table-column prop="overtimeHours" label="加班小时" width="200" />
        <el-table-column prop="month" label="月份" width="200" />
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 导入考勤对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入考勤数据"
      width="500px"
    >
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        drag
        :auto-upload="false"
        :on-change="handleFileChange"
        :show-file-list="true"
        accept=".xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><upload /></el-icon>
        <div class="el-upload__text">
          拖拽文件到此处或 <em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            仅支持 Excel 文件 (.xlsx, .xls)
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpload">导入</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑考勤对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增考勤记录' : '编辑考勤记录'"
      width="600px"
    >
      <el-form :model="attendanceForm" :rules="rules" ref="attendanceFormRef" label-width="100px">
        <el-form-item label="员工" prop="employeeId">
          <el-select v-model="attendanceForm.employeeId" placeholder="请选择员工" filterable>
            <el-option
              v-for="item in employeeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="attendanceForm.month"
            type="month"
            value-format="YYYY-MM"
            placeholder="选择月份"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="工作天数" prop="workDays">
          <el-input-number
            v-model="attendanceForm.workDays"
            :min="0"
            :max="31"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="迟到次数" prop="lateTimes">
          <el-input-number
            v-model="attendanceForm.lateTimes"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="早退次数" prop="leaveEarlyTimes">
          <el-input-number
            v-model="attendanceForm.leaveEarlyTimes"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="缺勤天数" prop="absentDays">
          <el-input-number
            v-model="attendanceForm.absentDays"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="加班小时" prop="overtimeHours">
          <el-input-number
            v-model="attendanceForm.overtimeHours"
            :min="0"
            :precision="1"
            :step="0.5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="attendanceForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import { getAttendancePage, importAttendance } from '@/api/attendance'

interface AttendanceRecord {
  id?: string
  employeeId: string
  employeeName: string
  department: string
  position: string
  workDays: number
  lateTimes: number
  leaveEarlyTimes: number
  absentDays: number
  overtimeHours: number
  month: string
  remark?: string
}

interface Employee {
  id: string
  name: string
  department: string
  position: string
}

// 搜索表单
const searchForm = reactive({
  employeeName: '',
  departmentId: 0,
  month: ''
})

// 表格数据
const tableData = ref<AttendanceRecord[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const importDialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const attendanceFormRef = ref()

const uploadRef = ref()

// 上传文件
const uploadFile = ref<File | null>(null)

// 考勤表单
const attendanceForm = reactive({
  employeeId: '',
  month: '',
  workDays: 0,
  lateTimes: 0,
  leaveEarlyTimes: 0,
  absentDays: 0,
  overtimeHours: 0,
  remark: ''
})

// 员工选项
const employeeOptions = ref<Employee[]>([
  { id: '1001', name: '张三', department: '技术部', position: '前端工程师' },
  { id: '1002', name: '李四', department: '市场部', position: '市场专员' },
  { id: '1003', name: '王五', department: '人事部', position: '人事专员' },
  { id: '1004', name: '赵六', department: '财务部', position: '会计' }
])

// 表单验证规则
const rules = {
  employeeId: [{ required: true, message: '请选择员工', trigger: 'change' }],
  month: [{ required: true, message: '请选择月份', trigger: 'change' }],
  workDays: [{ required: true, message: '请输入工作天数', trigger: 'blur' }]
}

// 模拟数据
const generateMockData = (): AttendanceRecord[] => {
  const departments = ['技术部', '市场部', '人事部', '财务部']
  const positions = ['前端工程师', '市场专员', '人事专员', '会计', '产品经理']
  
  return Array.from({ length: 20 }, (_, i) => {
    return {
      id: `ATT${String(i + 1).padStart(4, '0')}`,
      employeeId: `EMP${String(i + 1).padStart(4, '0')}`,
      employeeName: `员工${i + 1}`,
      department: departments[Math.floor(Math.random() * departments.length)],
      position: positions[Math.floor(Math.random() * positions.length)],
      workDays: 20 + Math.floor(Math.random() * 5),
      lateTimes: Math.floor(Math.random() * 3),
      leaveEarlyTimes: Math.floor(Math.random() * 2),
      absentDays: Math.floor(Math.random() * 2),
      overtimeHours: Math.floor(Math.random() * 20),
      month: '2024-01'
    }
  })
}

// 加载表格数据
const loadTableData = async () => {
  loading.value = true
  try {
    const response = await getAttendancePage({
      current: currentPage.value,
      size: pageSize.value,
      name: searchForm.employeeName,
      departmentId: searchForm.departmentId,
      month: searchForm.month
    })
    
    tableData.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取考勤数据失败:', error)
    ElMessage.error('获取考勤数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadTableData()
}

// 重置
const handleReset = () => {
  searchForm.employeeName = ''
  searchForm.department = ''
  searchForm.month = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  loadTableData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadTableData()
}

// 导入考勤
const handleImport = () => {
  importDialogVisible.value = true
  uploadRef.value.clearFiles()
}

// 文件选择
const handleFileChange = (file: any) => {
  console.log('选择文件:', file)
  uploadFile.value = file.raw
}

// 上传文件
const handleUpload = async () => {
  if (!uploadFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  
  ElMessage.success('正在导入考勤数据...')
  importDialogVisible.value = false
  
  try {
    // 调用导入API
    const resp = await importAttendance(uploadFile.value)
    if (resp) {
      ElMessage.success('导入成功')
      loadTableData()
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  }
  
  // 清空文件选择
  uploadFile.value = null
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(attendanceForm, {
    employeeId: '',
    month: '',
    workDays: 0,
    lateTimes: 0,
    leaveEarlyTimes: 0,
    absentDays: 0,
    overtimeHours: 0,
    remark: ''
  })
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row: AttendanceRecord) => {
  dialogType.value = 'edit'
  Object.assign(attendanceForm, {
    employeeId: row.employeeId,
    month: row.month,
    workDays: row.workDays,
    lateTimes: row.lateTimes,
    leaveEarlyTimes: row.leaveEarlyTimes,
    absentDays: row.absentDays,
    overtimeHours: row.overtimeHours,
    remark: row.remark || ''
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = async (row: AttendanceRecord) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除员工 ${row.employeeName} 的考勤记录吗？`,
      '删除确认',
      { type: 'warning' }
    )
    
    // 模拟删除操作
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
  } catch {
    // 取消删除
  }
}

// 详情
const handleDetail = (row: AttendanceRecord) => {
  ElMessage.info(`查看 ${row.employeeName} 的考勤详情`)
}

// 提交表单
const handleSubmit = async () => {
  if (!attendanceFormRef.value) return
  
  try {
    await attendanceFormRef.value.validate()
    
    if (dialogType.value === 'add') {
      // 模拟新增操作
      const employee = employeeOptions.value.find(e => e.id === attendanceForm.employeeId)
      const newRecord: AttendanceRecord = {
        id: `ATT${String(Date.now()).slice(-4)}`,
        employeeId: attendanceForm.employeeId,
        employeeName: employee?.name || '',
        department: employee?.department || '',
        position: employee?.position || '',
        workDays: attendanceForm.workDays,
        lateTimes: attendanceForm.lateTimes,
        leaveEarlyTimes: attendanceForm.leaveEarlyTimes,
        absentDays: attendanceForm.absentDays,
        overtimeHours: attendanceForm.overtimeHours,
        month: attendanceForm.month
      }
      tableData.value.unshift(newRecord)
      ElMessage.success('新增成功')
    } else {
      // 模拟编辑操作
      ElMessage.success('编辑成功')
    }
    
    dialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.attendance-container {
  padding: 20px;
}

.attendance-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table th) {
  /* background-color: #f5f7fa; */
  color: #606266;
  font-weight: 600;
}

:deep(.el-table .cell) {
  white-space: nowrap;
}

.upload-demo {
  text-align: center;
}

.el-upload__tip {
  margin-top: 10px;
  color: #606266;
  font-size: 12px;
}
</style>